package com.eclipse.e20200131_模拟连接池.com.qf.app1.m4;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class ConnectionPoolDataSource implements DataSource {
	private static Logger logger = LogManager.getLogger();

	// 池化
	private static List<Connection> pool = new ArrayList<>();

	private static Properties config = new Properties();

	private static String diverclass = null;

	private static String url = null;

	private static String userName = null;

	private static String password = null;

	// 记载配置文件，读取jdbc的配置信息
	static {
		try {
			config.load(JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties"));
			url = config.getProperty("jdbc.url");
			userName = config.getProperty("jdbc.username");
			password = config.getProperty("jdbc.password");
			diverclass = config.getProperty("jdbc.diverclass");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex);
		}
	}

	static {
		for (int i = 0; i < 5; i++) {
			// 1:加载驱动类
			try {
				Class.forName(diverclass);

				// 2: 打开连接
				Connection connection = DriverManager.getConnection(url, userName, password);
				pool.add(connection);
			} catch (Exception e) {
				logger.fatal(e);
			}

		}
	}

	/**
	 * 打开连接
	 * 
	 * @return
	 * @throws Exception
	 */
	@Override
	public Connection getConnection() {
		return pool.remove(pool.size() - 1);
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}
